package com.luobr.backend.manage.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import com.luobr.backend.common.ResponseCode;
import com.luobr.backend.constant.ImageConstant;
import com.luobr.backend.exception.BusinessException;
import com.luobr.backend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: 罗念笙
 * @date: 2025/3/2 15:08
 */
@Slf4j
@Service
public class UploadAndParseImage extends UploadAndParseImageTemplate {

    @Override
    public void validImage(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // 校验文件是否为空
        ThrowUtils.throwIf(ObjUtil.isNull(multipartFile), ResponseCode.PARAMS_ERROR, "文件不能为空");
        // 校验文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > ImageConstant.FILE_SIZE_LIMIT, new BusinessException(ResponseCode.PARAMS_ERROR, "文件大小不能超过 2M"));
        // 获取文件的后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 校验文件后缀，是否在 "jpeg", "jpg", "png", "webp" 中
        ThrowUtils.throwIf(!ImageConstant.ALLOW_UPLOAD_IMAGE_SUFFIX_FORMAT_LIST.contains(fileSuffix), new BusinessException(ResponseCode.PARAMS_ERROR, "文件类型错误"));
    }

    @Override
    public String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    public void processFile(Object inputSource, File file) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ResponseCode.SYSTEM_ERROR, "上传失败");
        }
    }
}
